<?php 

	class ProductsController extends AppController {
		var $name = 'Products';
		var $uses = array('Product', 'ProductTaxonomy');
		
		var $uploadImgPath;
		
		var $publicAction = array('index', 'details', 'collections');
		
		function beforeFilter() {
			parent::beforeFilter();
			$this->uploadImgPath = ROOT . DS . 'image' . DS . 'product' . DS . Configure::read('Shop.alias');
		}
		
		function index() {
			$this->pageTitle = __('Productos', true);
			
			$collections = $this->Product->collections(array('limit' => 20));
			
			$this->set(compact('collections'));
		}

		function details($slug = null) {
			$this->helpers[] = 'Number';
			
			if (empty($slug)) {
				$this->redirect(array('controller' => 'shops', 'action' => 'index'));
			}
			
			$details = $this->Product->details(0, $slug);
			
			if (empty($details)) {
				$this->Session->setFlash(__('El producto que intentas ver ya no existe.', true), 'default');
				$this->redirect(array('controller' => 'products', 'action' => 'index'));
			}
			
			$this->pageTitle = $details['ProductDescription']['name'];
			
			$this->set(compact('details'));
		}
		
		function collections($slug = null) {
			if (is_null($slug)) {
				$this->Product->Taxonomy->Behaviors->attach('Containable');
				$taxonomies = $this->Product->Taxonomy->find(
					'all',
					array(
						'conditions' => array(
							'Taxonomy.shop_id' => Configure::read('Shop.id'),
							'Taxonomy.disabled' => 0,
							'Taxonomy.deleted' => 0,
						),
						'contain' => array(
							'Term' => array(
								'slug'
							)
						),
						'recursive' => 0
					)
				);
				
				$this->set(compact('taxonomies'));
				
				$this->render('collections');
			}
			else {
				$this->helpers[] = 'Number';
				
				$data = $this->Product->Taxonomy->find(
					'first',
					array(
						'conditions' => array(
							'Term.slug' => $slug,
							'Taxonomy.shop_id' => Configure::read('Shop.id'),
							'Taxonomy.disabled' => 0
						),
						'fields' => array(
							'Term.slug',
							'Taxonomy.id',
							'Taxonomy.name'
						),
						'contain' => array(
							'Term'
						),
						'recursive' => 0
					)
				);
				
				if (empty($data)) {
					$this->redirect(array('controller' => 'products', 'action' => 'collections'));
				}
				
				$this->pageTitle = $data['Taxonomy']['name'];
				
				$this->paginate = array(
					'conditions' => array(
						'ProductTaxonomy.taxonomy_id' => $data['Taxonomy']['id'],
						'ProductTaxonomy.disabled' => 0,
					),
					'fields' => array(
					),
					'contain' => array(
						'Product' => array(
							'fields' => array(
								'Product.id',
								'Product.quantity',
								'Product.on_sale',
								'Product.price',
								'Product.show_price',
								'Product.model',
								'Product.code',
								'Product.width',
								'Product.height',
								'Product.depth',
								'Product.weight',
								'Product.preview',
								'Product.preview_pico',
								'Product.preview_icon',
								'Product.preview_tiny',
								'Product.preview_small',
								'Product.preview_compact',
								'Product.preview_medium',
								'Product.preview_large',
								'Product.preview_grande',
								'Product.preview_original',
								'Product.condition',
								'Product.available'
							),
							'Currency' => array(
								'fields' => array(
									'Currency.code',
									'Currency.symbol_left',
									'Currency.symbol_right',
									'Currency.decimal_places',
									'Currency.decimals',
									'Currency.thousands'
								)
							),
							'ProductDescription' => array(
								'fields' => array(
									'ProductDescription.slug',
									'ProductDescription.name',
									'ProductDescription.description',
									'ProductDescription.reference_url'
								)
							)
						)
					),
					'recursive' => 1
				);
				
				$products = $this->paginate('ProductTaxonomy');
				
				$this->set(compact('data', 'products'));
					
				$this->render('collections_products');
			}
		}
		
		function dashboard_index() {
			$this->pageTitle = __('Productos', true);
					
			// Revisamos si agrego categorías antes de publicar el primer producto.
			/*
			if (!$this->Product->Taxonomy->hasAny(array('Taxonomy.shop_id' => Configure::read('Shop.id'), 'Taxonomy.disabled' => 0, 'Taxonomy.deleted' => 0))) {
				$this->Session->setFlash(__('Es importante que tengas al menos una categoría para los articulos antes de comenzar a publicar.', true), null, array('class' => 'info'));
				$this->redirect(array('controller' => 'taxonomies', 'action' => 'dashboard_index'));
			}
			*/
			
			// Borramos la sesión del producto que se agrego.
			$this->Session->delete('Product');
			
			$products = $this->Product->collections($this, array('limit' => 10));
			
			$categories = $this->Product->Taxonomy->find(
				'list',
				array(
					'conditions' => array(
						'Taxonomy.shop_id' => Configure::read('Shop.id'),
						'Taxonomy.taxonomy' => 'category',
						'Taxonomy.deleted' => 0
					),
					'recursive' => -1
				)
			);
			
			$this->set(compact('products', 'categories'));
			
		}
		
		function dashboard_add() {
			$this->pageTitle = __('Agregar Producto', true);
			
			if (!$this->Session->check('Product.token')) {
				$this->Session->write('Product.token', Sanitize::paranoid(time()));
			}
			
			if (!empty($this->data)) {
				$this->Product->set($this->data);
				$this->Product->ProductDescription->set($this->data);
				
				$product = $this->Product->validates();
				$description = $this->Product->ProductDescription->validates();
				//$taxonomy = $this->Product->Taxonomy->validates();
				
				if ($product && $description) {
					$this->data['Product']['shop_id'] = Configure::read('Shop.id');
					
					if ($this->Session->check('Product.Preview')) {
						$this->data['Product']['preview'] = $this->Session->read('Product.Preview');
					}
					
					if ($this->Product->saveAll($this->data, array('validate' => false))) {
						// Mover imagenes de temporales.
						$this->__images();
						
						$this->Session->setFlash(__('Se agrego exitosamente el producto.', true), null, array('class' => 'success'));
						$this->redirect(array('controller' => 'products', 'action' => 'dashboard_index'));
					}
				}
			}
			
			//$this->__categories();
			
			$categories = $this->Product->Taxonomy->find(
				'threaded',
				array(
					'conditions' => array(
						'Taxonomy.shop_id' => Configure::read('Shop.id'),
						'Taxonomy.taxonomy' => 'category',
						'Taxonomy.deleted' => 0 
					),
					'fields' => array(
						'Taxonomy.id',
						'Taxonomy.parent_id',
						'Taxonomy.name',
						'Taxonomy.disabled'
					),
					'recursive' => -1
				)
			);
			
			$this->set(compact('categories'));
			
			$this->set('currencies', $this->Product->Currency->find('list', array('conditions' => array('Currency.disabled' => 0, 'Currency.deleted' => 0))));
			
			$this->helpers[] = 'Dashboard';
			$this->render('dashboard_form');
		}
		
		function dashboard_edit($id, $idEncrypt) {
			$this->pageTitle = __('Editar Producto', true);
			
			if (Security::hash($id, 'md5', true) != $idEncrypt) {
				$this->Session->setFlash(__('Es imposible editar el producto, solo guíate por los links del panel de administración.', true), null, array('class' => 'warning'));
				$this->redirect(array('controller' => 'products', 'action' => 'index'));
			}
			
			if (!empty($this->data)) {
				$this->Product->set($this->data);
				$this->Product->ProductDescription->set($this->data);
				
				$product = $this->Product->validates();
				$description = $this->Product->ProductDescription->validates();
				
				if ($product && $description) {
					if ($this->Session->check('Product.Preview')) {
						$this->data['Product']['preview'] = $this->Session->read('Product.Preview');
					}
					if ($this->Product->saveAll($this->data, array('validate' => false))) {
						// Mover imagenes de temporales.
						$this->__images();
						
						$this->Session->setFlash(__('Se edito exitosamente el articulo.', true), null, array('class' => 'alert'));
						$this->redirect(array('controller' => 'products', 'action' => 'dashboard_index'));
					}
				}
			}
			
			$this->Product->contain(
				array(
					'Currency',
					'ProductDescription',
					'ProductImage' => array(
						'fields' => array(
							'ProductImage.id',
							'ProductImage.filename',
							'CONCAT(\''. Configure::read('Site.Url.image') . '/product/' . Configure::read('Shop.alias') . '/' .'\', REPLACE(ProductImage.filename,\'.\',\'_medium.\')) AS filename_path'
						)
					),
					'Taxonomy' => array(
						'fields' => array(
							'id',
							'parent_id'
						)
					)
				)
			);
			
			$this->Product->recursive = 1;
			$this->data = $this->Product->read(
				array(
					'Product.id',
					'Product.currency_id',
					'Product.quantity',
					'Product.code',
					'Product.price',
					'Product.preview',
					'ProductDescription.id',
					'ProductDescription.name',
					'ProductDescription.description',
					'Currency.symbol_left',
					'Currency.symbol_right',
					'Currency.decimal_places',
					'Currency.decimals',
					'Currency.thousands'
				),
				$id
			);
			// pr($this->data);
			// Remover cuando se utilize multicategoría para los productos
			if (!empty($this->data['Category'][0])) {
				$this->data['Product']['taxonomy'] = $this->data['Taxonomy'][0]['parent_id'];
				$this->data['Taxonomy']['Taxonomy'][] = $this->data['Taxonomy'][0]['id'];
			}
			
			$categories = $this->Product->Taxonomy->find(
				'threaded',
				array(
					'conditions' => array(
						'Taxonomy.shop_id' => Configure::read('Shop.id'),
						'Taxonomy.taxonomy' => 'category'
					)
				)
			);
			
			$this->set(compact('categories'));

			$this->set('currencies', $this->Product->Currency->find('list', array('conditions' => array('Currency.disabled' => 0, 'Currency.deleted' => 0))));
			
			$this->helpers[] = 'Dashboard';
			$this->render('dashboard_form');
		}
		
		function dashboard_delete($id, $idEncrypt) {
			$this->autoRender = false;
			
			if (Security::hash($id, 'md5', true) != $idEncrypt) {
				$this->Session->setFlash(__('Es imposible eliminar el articulo, solo guíate por los links del administrador.', true), null, array('class' => 'warning'));
				$this->redirect(array('controller' => 'products', 'action' => 'dashboard_index'));
			}
			
			$request = array();
			
			$product_description_condition = $product_description_update = $product_images_ondition = $product_images_update = array();
			
			$this->data['Product']['id'] = $product_description_conditions['ProductDescripction']['product_id'] = $product_images_conditions['ProductImages.product_id'] = $id;
			$this->data['Product']['deleted'] = $product_description_update['ProductDescripction.deleted'] = $product_images_update['ProductImages.deleted'] = 1;
			if ($this->Product->save($this->data, false)) {
				$this->Product->ProductDescription->updateAll(
					array(
						'ProductDescription.deleted' => 1
					),
					array(
						'ProductDescription.product_id' => $id
					)
				);
				$this->Product->ProductImage->updateAll(
					array(
						'ProductImage.deleted' => 1
					),
					array(
						'ProductImage.product_id' => $id
					)
				);
				
				$this->Product->ProductTaxonomy->recursive = -1;
				$this->Product->ProductTaxonomy->updateAll(
					array(
						'ProductTaxonomy.deleted' => 1
					),
					array(
						'ProductTaxonomy.product_id' => $id
					)
				);
				
				if ($this->params['isAjax']) {
					return htmlspecialchars(json_encode($request), ENT_NOQUOTES);
				} else {
					$this->Session->setFlash(__('El articulo fue eliminado exitosamente.', true), null, array('class' => 'success'));
					$this->redirect(array('controller' => 'products', 'action' => 'dashboard_index'));
				}
				
			}
		}
	
		function dashboard_details($id, $idEncrypt) {
			$this->set('details', $this->Product->details($id));
		}
		
		private function __categories() {
			$categories = $this->Product->Taxonomy->find(
				'list',
				array(
					'conditions' => array(
						'Taxonomy.shop_id' => Configure::read('Shop.id'),
						'Taxonomy.deleted' => 0,
						'Taxonomy.disabled' => 0,
						//
						'Taxonomy.parent_id' => 0,
						'Taxonomy.taxonomy' => 'category'
					),
					'recursive' => -1
				)
			);
			
			$this->set('categories', $categories);
		}
		
		private function __images() {
			if ($this->Session->check('Product.Images')) {
				$this->uploadImgPath.= DS . $this->Product->id;
				
				foreach($this->Session->read('Product.Images') AS $key => $image) {
					$this->data['ProductImage']['product_id'] = $this->Product->id;
					$this->data['ProductImage']['path'] = $this->uploadImgPath;
					
					list($product_id, $shop_alias) = current(array_chunk(array_reverse(explode(DS, $this->uploadImgPath)), 2));
					
					$this->data['ProductImage']['path_url'] = '/product/' . $shop_alias . '/' . $product_id;
					$this->data['ProductImage']['filename'] = $image['file'];
					
					$this->Product->ProductImage->id = null;
					$this->Product->ProductImage->save($this->data);
					
					// Marcar la primera imagen como predeterminada para el producto
					// solo si no tiene la sessión de Preview.
					if ($key == 0 && !$this->Session->check('Product.Preview')) {
						$this->Session->write('Product.Preview', $this->data['ProductImage']['path_url'] . '/' . $this->data['ProductImage']['filename']);
					}
					
					if (!is_dir($this->uploadImgPath) && !file_exists($this->uploadImgPath)) {
						@mkdir($this->uploadImgPath, 0777, true);
					}
					
					$fileinfo = pathinfo($image['file']);
					
					foreach(glob($image['path'] . DS . $fileinfo['filename'] . '*') AS $filename) {
						@rename($filename, $this->uploadImgPath . DS . basename($filename));
					}
				}
			}
		}
	}
